package com.buyingtickets.service.impl;

import com.buyingtickets.dao.*;
import com.buyingtickets.entity.*;
import com.buyingtickets.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author bwj
 * @date 2021/6/24 9:09
 */
@Service
public class TrainServiceImpl implements TrainService {
    @Resource
    private TrainDao trainDao;
    @Autowired
    private SiteDao siteDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private UnitIntervalDao unitIntervalDao;
    @Autowired
    private StopoverStationDao stopoverStationDao;
    @Autowired
    private CarriageInformationService carriageInformationService;
    @Autowired
    private InitialSeatDao initialSeatDao;
    @Autowired
    private CarriageService carriageService;
    @Autowired
    private UnitIntervalBiz unitIntervalBiz;

    @Override
    public Train queryByTrainID(int trainid) {

        return trainDao.queryByTrainID(trainid);
    }

    @Override
    public List<Train> queryByTrainIDOrName(String trainidname, int page) {
        if (page > 0) {
            page = 5 * (page - 1);
        }
        return trainDao.queryByTrainIDOrName("%" + trainidname + "%", page);
    }

    @Override
    public List<Train> queryByTrainAll(int page) {
        if (page > 0) {
            page = 5 * (page - 1);
        }
        return trainDao.queryByTrainAll(page);
    }

    @Override
    public int queryCount() {
        return trainDao.queryCount();
    }

    @Override
    public int queryCountByName(String trainidname) {
        if (StringUtils.hasText(trainidname)) {
            return trainDao.queryCountByName("%" + trainidname + "%");
        }
        return -1;
    }

    /**
     * 添加列车
     *
     * @param route
     * @return
     */
    @Override
    public boolean addTrain(Route route) {
        String trainname = route.getTrainname();//列车名
        String date = route.getDate();//出发时间
        int type = route.getTraintype();//列车类型
        String site = route.getSite();//站点
        int row = route.getRow();//车厢排数
        int col = route.getCol();//车厢列数
        int price = route.getPrice();//里程价格
        int carriagenum = route.getCarriagenum();//车厢个数

        int sttype = typeDao.queryByClassAndName("列车状态类型", "正常");
        if (StringUtils.hasText(trainname) && StringUtils.hasText(site)) {
            String[] sites = site.split(",");//站点集合
            int[] siteids = new int[sites.length];
            for (int i = 0; i < siteids.length; i++) {
                if (siteDao.queryBySiteName(sites[i]).size() > 0) {
                    siteids[i] = siteDao.queryBySiteName(sites[i]).get(0).getSiteId();
                }
            }
            //添加列车
            if (siteids[0] != 0 || siteids[siteids.length - 1] != 0) {
                trainDao.addTrain(trainname, type, siteids[0],
                        siteids[siteids.length - 1], sttype, price, date);
            } else {
                return false;
            }
            int trainid = trainDao.queryByTrainLast();
            //添加车厢信息

            for (int i = 0; i < carriagenum; i++) {
                int cxtype = 20;
                if (i == 0) {
                    cxtype = 17;
                }
                if (i != 0 && i < 4) {
                    cxtype = 20;
                }
                if (i >= 4 && i != 0 && i <= 6) {
                    cxtype = 19;
                }
                if (i != 0 && i > 6) {
                    cxtype = 20;
                }
                //添加车厢详细信息
                carriageInformationService.addCarriage(row, col, cxtype);

                //车厢详细信息id
                int j = carriageInformationService.queryCinfoIDLast();
                //添加车厢
               carriageService.addCarriage(trainid, j, i);
//                int m=carriageService.queryIdLast();
                for (int x = 0; x < row; x++) {
                    for (int y = 0; y < col; y++) {
                        char coltype = (char) (y + 'A');

                        initialSeatDao.addInitialSeat(trainid, i + 1, x + 1, coltype + "");
                    }
                }
            }

            String travelTime = "00:00";
            for (int i = 0; i < sites.length; i++) {//添加经停站
                List<UnitInterval> unitIntervals = null;
                int unitid = 1;
                try {
                    if (i == 0) {
                        unitIntervals = unitIntervalDao.queryByStartAndEnd(siteids[i], siteids[i]);
                        if (unitIntervals.size() == 0) {
//                            UnitInterval u = new UnitInterval();
//                            Site s = new Site();
//                            s.setSiteId(siteDao.queryByName(sites[i]));
//                            u.setStartsite(s);
//                            u.setEndsite(s);
                            unitIntervalBiz.addUnitInterval(siteids[i],siteids[i],0,"00:00");
                            unitIntervals = unitIntervalDao.queryByStartAndEnd(siteids[i], siteids[i]);
                        }
                    } else {
                        unitIntervals = unitIntervalDao.queryByStartAndEnd(siteids[i - 1], siteids[i]);
                    }
                    if(unitIntervals!=null){
                        unitid = unitIntervals.get(0).getUnitId();
                        travelTime = dateUtil(travelTime, unitIntervals.get(0).getTravelTime());
                    }

                     stopoverStationDao.addStopoverStation(trainid, unitid, i + 1,
                            siteDao.queryBySiteName(sites[i]).get(0).getSiteId(), travelTime);

                } catch (Exception e) {
                    e.printStackTrace();
                    return true;
                }

            }
        }
        return true;
    }

    @Override
    public int queryByTrainLast() {
        return trainDao.queryByTrainLast();
    }

    public String dateUtil(String str1, String str2) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        if(!StringUtils.hasText(str2)||"0:0".equals(str2)){
            str2="00:00";
        }
        try {
            long n = (sdf.parse(str1).getTime() + sdf.parse(str2).getTime()+sdf.parse("24:00").getTime()) / 1000;
            long hour = 0;
            long second = 0;
            hour = n / 60 / 60;
            second = n / 60 % 60;
            return hour + ":" + second;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

}
